<script setup lang="ts">
import { ref, nextTick, onMounted } from "vue";
import { centerMap, GETNOBASE } from "@/api";
import { registerMap, getMap } from "echarts/core";
import { optionHandle, regionCodes } from "./center.map";
import BorderBox13 from "@/components/datav/border-box-13";
import { ElMessage } from "element-plus";
import type { MapdataType } from "./center.map";
import { initMock, centerMapRef } from "./useAddMockMap";
import $http from "@/api/apiMap";
import VNumberScroll from "@/components/VNumberScroll.vue";
const option = ref({});
const code = ref("350000"); // china 代表中国 其他地市是行政编码
withDefaults(
    defineProps<{
        // 结束数值
        title?: number | string;
    }>(),
    {
        title: "",
    }
);

const count = ref(0);

const emit = defineEmits<{
    mapAnimationEnd: [params: { id: number; cityName: string }];
}>();
// list 元素的形状（根据你的实际接口调整）
interface ListItem {
    name: string;
    number: number; // 或者 value: number，保持一致即可
    accountNum: number; // 用户数
}

/**
 * 根据 regionCode 与业务数据 list 生成 ECharts 地图 option
 * @param regionCode  行政区代码
 * @param list        业务数据（带 name 和数值）
 */
const dataSetHandle = async (regionCode: string, list: ListItem[]): Promise<void> => {
    // 1. 取 GeoJSON
    const geojson: any = await getGeojson(regionCode);
    // 2. 建立城市名 -> 中心点索引
    const cityCenter: Record<string, [number, number]> = {};
    geojson.features.forEach((feature: any) => {
        const { name, centroid, center } = feature.properties as any;
        cityCenter[name] = center ?? centroid;
    });
    $http.get_city_account_static({}).then(async res => {
        const accountData = res.data;
        const newList = list.map(item => {
            item.accountNum = getCityNumber(accountData, item.name);
            return item;
        });
        // 3. 拼出散点数据
        const mapData: MapdataType[] = newList
            .filter(item => cityCenter[item.name]) // 确保能找到中心点
            .map(item => ({
                name: item.name,
                value: [...cityCenter[item.name]] as [number, number],
            }));
        // 4. 等待 DOM 更新（如果你用的是 Vue3 Composition API）
        await nextTick();
        // 5. 生成最终 option
        option.value = optionHandle(regionCode, newList, mapData);
    });
};

// 城市数据项结构
interface CityItem {
    city: string;
    accountNum: number;
}

/**
 * 根据城市名关键字返回对应 accountNum 之和
 * @param allData 城市数据列表
 * @param cityName 要匹配的城市名关键字（支持模糊）
 */
function getCityNumber(allData: CityItem[], cityName: string): number {
    // 空值兜底
    if (!Array.isArray(allData) || !cityName) return 0;

    return allData
        .filter(
            (item): item is CityItem => item != null && typeof item.city === "string" && typeof item.accountNum === "number" && item.city.includes(cityName) // 模糊匹配
        )
        .reduce((sum, cur) => sum + cur.accountNum, 0);
}

const getData = async (regionCode: string) => {
    centerMap({ regionCode: regionCode })
        .then(res => {
            if (res.success) {
                dataSetHandle(res.data.regionCode, res.data.dataList);
            } else {
                ElMessage.error(res.msg);
            }
        })
        .catch(err => {
            ElMessage.error(err);
        });
};
const getGeojson = (regionCode: string) => {
    return new Promise<boolean>(async resolve => {
        let mapjson = getMap(regionCode);
        if (mapjson) {
            mapjson = mapjson.geoJSON;
            resolve(mapjson);
        } else {
            mapjson = await GETNOBASE(`./map-geojson/${regionCode}.json`).then(data => data);
            code.value = regionCode;
            registerMap(regionCode, {
                geoJSON: mapjson as any,
                specialAreas: {},
            });
            resolve(mapjson);
        }
    });
};


const mapClick = (params: any) => {
    let xzqData = regionCodes[params.name];
    if (xzqData) {
        getData(xzqData.adcode);
    } else {
        window["$message"].warning("暂无下级地市");
    }
};

// 得到今日交易数
const getTodayTransaction = ()=>{
    $http.get_today_order_total({}).then(res=>{
        const total = res.data.total;
        count.value = total;
    })
} 

// 初始化地图动画mock
onMounted(() => {
    getData(code.value);
    getTodayTransaction();
    initMock((id: number, cityName: string) => {
        emit("mapAnimationEnd", { id, cityName });
    });
});
</script>

<template>
    <div class="centermap">
        <div class="maptitle">
            <div class="flex flex-btw flex-align-center">
                <span class="no-white">今日交易额</span>
                <VNumberScroll :digitRatio="0.5" :value="count" :duration="1.5" :int-len="6" :decimals="0" />
            </div>
        </div>
        <div class="mapwrap">
            <BorderBox13>
                <div class="quanguo" @click="getData('china')" v-if="code !== 'china'">中国</div>
                <v-chart class="chart" :option="option" ref="centerMapRef" @click="mapClick" v-if="JSON.stringify(option) != '{}'" />
            </BorderBox13>
        </div>
    </div>
</template>

<style scoped lang="scss">
.centermap {
    margin-bottom: 20px;

    .maptitle {
        height: 90px;
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        background-image: url("@/assets/image/echarts-header.png");
        background-repeat: no-repeat;
        background-size: contain;
        background-position: center;
        position: relative;
        & > div {
            position: absolute;
            width: 240px;
            height: 100%;
            span {
                font-size: 14px;
                font-weight: bold;
            }
            span.big {
                font-size: 20px;
            }
        }
    }

    .mapwrap {
        height: 580px;
        width: 100%;
        box-sizing: border-box;
        position: relative;
        .quanguo {
            position: absolute;
            right: 20px;
            top: -46px;
            width: 80px;
            height: 28px;
            border: 1px solid #00eded;
            border-radius: 10px;
            color: #00f7f6;
            text-align: center;
            line-height: 26px;
            letter-spacing: 6px;
            cursor: pointer;
            box-shadow:
                0 2px 4px rgba(0, 237, 237, 0.5),
                0 0 6px rgba(0, 237, 237, 0.4);
            z-index: 10;
        }
    }
}
</style>
